package com.ywz.project.system.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ywz.common.ResultResp;
import com.ywz.common.StringUtils;
import com.ywz.common.TreeListUtils;
import com.ywz.project.base.system.entity.TSysMenu;
import com.ywz.project.base.system.entity.TSysMenuSub;
import com.ywz.project.base.system.service.ITSysMenuSubService;
import com.ywz.project.base.system.service.TSysMenuService;
import com.ywz.project.system.service.MenuSubApiService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class MenuSubApiServiceImpl implements MenuSubApiService {
    @Resource
    private ITSysMenuSubService iTSysMenuSubService;
    @Resource
    private TSysMenuService tSysMenuService;

    @Override
    public ResultResp getMenuSubListByRemark(String remark) {
        if (StringUtils.isEmpty(remark))
            return ResultResp.error("不存在子菜单");
        List<TSysMenuSub> respList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(remark)) {
            map.put("topId", 0);
            map.put("list", respList);
        }
        LambdaQueryWrapper<TSysMenuSub> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSysMenuSub::getIsDeleted, 0);
        if (!remark.equals("all")) {
            wrapper.eq(TSysMenuSub::getRemark, remark);
        }
        List<TSysMenuSub> list = iTSysMenuSubService.list(wrapper);
        // 获取父节点pid
        Set<String> collect = list.stream().filter(tSysMenuSub -> tSysMenuSub.getIsParent() == 1).map(TSysMenuSub::getParentId).collect(Collectors.toSet());
        for (String s : collect) {
            // 将菜单转成Tree结构
            List<TSysMenuSub> tSysMenuSubs = TreeListUtils.listToTree(list, TSysMenuSub.class, "id", "parentId", s, "children");
            tSysMenuSubs.sort(Comparator.comparing(TSysMenuSub::getSort));
            tSysMenuSubs.forEach(tSysMenu -> {
                tSysMenu.getChildren().sort(Comparator.comparing(TSysMenuSub::getSort));
            });
            respList.addAll(tSysMenuSubs);
        }
        map.put("topId", 0);
        map.put("list", respList);
        return ResultResp.success(map);
    }

    @Override
    public ResultResp saveMenuSub(String req) {
        if (StringUtils.isEmpty(req))
            return ResultResp.error("参数错误");
        JSONObject jsonObject = JSONUtil.parseObj(req);
        // 获取集合列表
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        // 保存的数据
        List<TSysMenuSub> list = new ArrayList<>();
        AtomicInteger sort = new AtomicInteger(1);
        AtomicReference<String> parentId = new AtomicReference<>("");
        jsonArray.forEach(json -> {
            TSysMenuSub menu = JSONUtil.toBean(json.toString(), TSysMenuSub.class);
            parentId.set(menu.getRemark());
            String id = parentId.get() + "00" + sort.get();
            menu.setId(id);
            menu.setParentId(menu.getRemark());
            menu.setSort(sort.get());
            // 二级菜单
            if (!TreeListUtils.isEmpty(menu.getChildren())) {
                List<TSysMenuSub> children = menu.getChildren();
                AtomicInteger childSort = new AtomicInteger(1);
                children.forEach(child -> {
                    child.setId(id + "00" + childSort.get());
                    child.setParentId(id);
                    child.setSort(childSort.getAndIncrement());
                    child.setUpdatedTime(LocalDateTime.now());
                    list.add(child);
                });
            }
            menu.setUpdatedTime(LocalDateTime.now());
            list.add(menu);
            sort.getAndIncrement();
        });

        // 校验关联
        AtomicBoolean flag = new AtomicBoolean(true);
        Set<String> menuSubRemarkSet = list.stream().map(tSysMenuSub -> {
            String remark = tSysMenuSub.getRemark();
            if (StringUtils.isEmpty(remark))
                flag.set(false);
            return remark;
        }).collect(Collectors.toSet());
        if (!flag.get())
            return ResultResp.error("关联菜单不能为空");
        List<TSysMenu> menuList = tSysMenuService.list();
        Set<String> menuRemarkSet = menuList.stream().map(TSysMenu::getRemark).filter(remark -> !StringUtils.isEmpty(remark)).collect(Collectors.toSet());
        if (!menuRemarkSet.containsAll(menuSubRemarkSet))
            return ResultResp.error("关联菜单不存在");

        // 保存数据
        LambdaUpdateWrapper<TSysMenuSub> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(TSysMenuSub::getIsDeleted, 0);
        wrapper.in(TSysMenuSub::getRemark, menuSubRemarkSet);
        iTSysMenuSubService.remove(wrapper);
        iTSysMenuSubService.saveBatch(list);
        return ResultResp.success();
    }
}
